#!/usr/bin/perl

# Copyright © 2014 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

use v5.10;

use strict;
use warnings;

no lib '.';

use English qw(-no_match_vars);
use FindBin ();
use Pod::Simple::XHTML ();

my $html;
my $psx = Pod::Simple::XHTML->new;
$psx->output_string(\$html);
$psx->html_charset('UTF-8');
$psx->html_encode_chars('&<>">');
$psx->parse_file("$FindBin::Bin/../doc/manual.pod");

sub quote_b
{
    local ($_) = @_;
    if (m{[_/]} or ($_ eq 'LANG') or ($_ eq '*')) {
        s/\A([^<]+)/`$1`/;
        s/>\K([^<]+)/`$1`/g;
    }
    return $_;
}

$html =~ s{.*<body>\s*}{}s or die 'Failed to strip leading curft';
$html =~ s{</body>.*}{}s or die 'Failed to strip trailing cruft';
$html =~ s{</?code>}{}g or die 'Failed to strip <code>';
$html =~ s{&gt;}{>}g or die 'Failed to unquote &gt;';
$html =~
    s{\b\Qhttp://man.he.net/man1/gpg\E\b}
    {https://www.gnupg.org/documentation/manpage.html}g
    or die 'Failed to fix the GnuPG manpage link';
$html =~
    s{\b\Qhttp://man.he.net/man7/locale\E\b}
    {http://man7.org/linux/man-pages/man7/locale.7.html}
    or die 'Failed to fix the locale(7) manpage link';
$html =~ s{<b>\K(.*?)(?=</b>)}{quote_b($1)}eg;

binmode(STDOUT, ':encoding(UTF-8)')
    or die $ERRNO;
print("#labels Featured\n\n");
print($html);
close(STDOUT)
    or die $ERRNO;

# vim:ts=4 sts=4 sw=4 et
